<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>用户信息评估 - n8n工作流监控系统</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Microsoft YaHei', '微软雅黑', Arial, sans-serif;
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .container { max-width: 1400px; margin: 0 auto; }
        .header {
            text-align: center;
            color: white;
            margin-bottom: 30px;
        }
        .header h1 { font-size: 2.5em; margin-bottom: 10px; }
        .back-btn {
            background: white; color: #059669; border: none;
            padding: 12px 30px; border-radius: 25px;
            font-size: 1em; font-weight: bold; cursor: pointer;
            margin-top: 15px; transition: all 0.3s;
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
        }
        .back-btn:hover { transform: translateY(-2px); }
        .main-section {
            background: white; border-radius: 15px; padding: 40px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            text-align: center;
        }
        .evaluate-btn {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white; border: none; padding: 20px 50px;
            border-radius: 50px; font-size: 1.3em; font-weight: bold;
            cursor: pointer; transition: all 0.3s;
            box-shadow: 0 4px 15px rgba(0,0,0,0.2); margin: 30px 0;
        }
        .evaluate-btn:hover { transform: translateY(-3px); }
        .evaluate-btn:disabled { background: #ccc; cursor: not-allowed; transform: none; }
        .info-text {
            background: #e3f2fd; border-left: 4px solid #2196f3;
            padding: 15px 20px; margin: 20px 0; border-radius: 5px;
            text-align: left; color: #1976d2;
        }
        .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin: 20px 0; }
        .stat-card { background: #f8f9fa; border-radius: 10px; padding: 20px; text-align: center; }
        .stat-card .label { font-size: 0.9em; color: #666; margin-bottom: 10px; }
        .stat-card .value { font-size: 2em; font-weight: bold; color: #667eea; }
        .message-list { margin-top: 30px; }
        .message-item {
            background: #fef2f2; border-left: 4px solid #ef4444;
            padding: 15px; margin-bottom: 15px; border-radius: 5px;
        }
        .loading { text-align: center; padding: 50px; font-size: 1.5em; color: #666; }
        .view-chat-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(99, 102, 241, 0.5) !important;
        }
        .view-chat-btn:active {
            transform: translateY(0);
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>👤 用户信息评估</h1>
            <button class="back-btn" onclick="window.location.href='index.html'">← 返回主页</button>
        </div>
        
        <div class="main-section">
            <h2>开始用户消息评估</h2>
            <p style="color: #666; margin: 20px 0;">检测用户消息中的敏感信息（骂人、生气、政治敏感等）</p>
            
            <div class="info-text">
                ⚠️ 此功能将评估候选人发送的消息，检测是否存在不文明用语、政治敏感内容等。
                <br>将先通过关键词筛选，然后使用AI进行深入分析。
            </div>
            
            <button class="evaluate-btn" id="evaluateBtn" onclick="startEvaluation()">
                🚀 开始评估
            </button>
            
            <div id="progressSection" class="loading" style="display: none;">
                <div class="progress-bar">
                    <div class="progress-fill" style="width: 0%;">0%</div>
                </div>
                <p id="progressText">准备开始...</p>
            </div>
            
            <div id="statsSection" class="stats-grid" style="display: none;">
                <div class="stat-card">
                    <div class="label">总消息数</div>
                    <div class="value" id="totalMessages">0</div>
                </div>
                <div class="stat-card">
                    <div class="label">关键词筛选</div>
                    <div class="value" id="keywordFiltered">0</div>
                </div>
                <div class="stat-card">
                    <div class="label">AI评估成功</div>
                    <div class="value" id="aiEvaluated">0</div>
                </div>
                <div class="stat-card">
                    <div class="label">敏感消息</div>
                    <div class="value" id="sensitiveMessages">0</div>
                </div>
                <div class="stat-card">
                    <div class="label">转人工请求</div>
                    <div class="value" id="transferRequests">0</div>
                </div>
                <div class="stat-card">
                    <div class="label">正常消息</div>
                    <div class="value" id="normalMessages">0</div>
                </div>
            </div>
            
            <div id="resultSection" class="message-list" style="display: none;">
                <h3 style="text-align: left; margin-bottom: 20px;">敏感消息列表</h3>
                <div id="messageList"></div>
            </div>
            
            <button id="exportBtn" onclick="exportResults()" style="display: none; background: #10b981; color: white; border: none; padding: 15px 40px; border-radius: 10px; font-size: 1.1em; cursor: pointer; margin-top: 30px;">
                📥 导出结果
            </button>
        </div>
    </div>
    
    <script>
        let evaluationData = null;
        
        async function startEvaluation() {
            const btn = document.getElementById('evaluateBtn');
            btn.disabled = true;
            btn.textContent = '评估中...';
            document.getElementById('progressSection').style.display = 'block';
            
            updateProgress(10, '正在连接服务器...');
            
            try {
                const response = await fetch('/api/evaluate-user-messages', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ limit: 10 })
                });
                
                updateProgress(30, '开始评估消息...');
                
                if (!response.ok) {
                    throw new Error(`服务器错误: ${response.status}`);
                }
                
                const data = await response.json();
                evaluationData = data;
                
                updateProgress(70, '正在整理结果...');
                await new Promise(resolve => setTimeout(resolve, 200));
                
                updateProgress(100, '评估完成！');
                
                displayResults(data);
                document.getElementById('evaluateBtn').style.display = 'none';
                document.getElementById('exportBtn').style.display = 'block';
                
            } catch (error) {
                alert(`评估失败: ${error.message}`);
                btn.disabled = false;
                btn.textContent = '🚀 开始评估';
            }
        }
        
        function updateProgress(percent, text) {
            document.querySelector('.progress-fill').style.width = percent + '%';
            document.getElementById('progressText').textContent = text;
        }
        
        function displayResults(data) {
            document.getElementById('statsSection').style.display = 'grid';
            document.getElementById('resultSection').style.display = 'block';
            
            // 显示统计信息
            document.getElementById('totalMessages').textContent = data.total_messages || 0;
            document.getElementById('keywordFiltered').textContent = data.keyword_filtered_count || 0;
            document.getElementById('aiEvaluated').textContent = data.ai_evaluated_count || 0;
            document.getElementById('sensitiveMessages').textContent = data.sensitive_messages_count || 0;
            document.getElementById('transferRequests').textContent = data.transfer_request_count || 0;
            document.getElementById('normalMessages').textContent = data.normal_messages_count || 0;
            
            // 收集需要显示的消息（敏感消息 + 转人工请求）
            const messageList = document.getElementById('messageList');
            const allEvaluations = data.all_evaluations || [];
            
            const highlightMessages = allEvaluations.filter(msg => {
                const eval = msg.evaluation || {};
                return eval.is_sensitive || eval.is_transfer_request;
            });
            
            // 修复统计：确保显示的消息数量与统计一致
            console.log(`敏感消息统计: ${data.sensitive_messages_count}, 实际筛选: ${highlightMessages.length}`);
            
            if (highlightMessages.length === 0) {
                messageList.innerHTML = '<div class="loading">✅ 未发现敏感消息或转人工请求</div>';
            } else {
                messageList.innerHTML = highlightMessages.map(msg => {
                    const eval = msg.evaluation || {};
                    const isSensitive = eval.is_sensitive;
                    const isTransfer = eval.is_transfer_request;
                    
                    let tags = [];
                    if (isSensitive) tags.push('<span style="background:#ef4444;color:white;padding:2px 8px;border-radius:4px;margin-right:5px;">敏感</span>');
                    if (isTransfer) tags.push('<span style="background:#f59e0b;color:white;padding:2px 8px;border-radius:4px;margin-right:5px;">转人工</span>');
                    
                    const keywords = eval.detected_keywords || {};
                    let keywordInfo = '';
                    if (keywords.sensitive && keywords.sensitive.length > 0) {
                        keywordInfo += `敏感词: ${keywords.sensitive.join(', ')}`;
                    }
                    if (keywords.transfer_to_human && keywords.transfer_to_human.length > 0) {
                        if (keywordInfo) keywordInfo += ' | ';
                        keywordInfo += `转人工词: ${keywords.transfer_to_human.join(', ')}`;
                    }
                    
                    // 格式化时间
                    const timeStr = msg.created_at ? new Date(msg.created_at).toLocaleString('zh-CN') : '未知';
                    
                    return `
                        <div class="message-item" style="position: relative; padding: 15px; margin-bottom: 15px; background: #f9fafb; border-radius: 8px; border-left: 4px solid ${isSensitive ? '#ef4444' : '#f59e0b'};">
                            <div style="margin-bottom: 8px;">${tags.join('')}</div>
                            <div style="display: flex; justify-content: space-between; align-items: start;">
                                <div style="flex: 1;">
                                    <strong style="font-size: 1.1em; color: #1f2937;">${msg.candidate_name}</strong>
                                    <small style="color: #6b7280; margin-left: 10px;">📅 ${timeStr}</small>
                                    <br><br>
                                    <div style="color: #374151; line-height: 1.6;">${msg.content}</div>
                                    <br>
                                    <small style="color: #6b7280;">评分: ${eval.score || 0} | ${eval.reason || ''}</small><br>
                                    ${keywordInfo ? `<small style="color:#6b7280;">${keywordInfo}</small>` : ''}
                                </div>
                                <div style="margin-left: 15px;">
                                    <button onclick="viewChatHistory(${msg.candidate_id}, '${msg.candidate_name.replace(/'/g, "\\'")}')" 
                                            class="view-chat-btn"
                                            style="background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%); 
                                                   color: white; 
                                                   border: none; 
                                                   padding: 10px 20px; 
                                                   border-radius: 8px; 
                                                   cursor: pointer; 
                                                   font-size: 0.9em;
                                                   box-shadow: 0 2px 8px rgba(99, 102, 241, 0.3);
                                                   transition: all 0.3s;
                                                   white-space: nowrap;">
                                        💬 查看聊天记录
                                    </button>
                                </div>
                            </div>
                        </div>
                    `;
                }).join('');
            }
        }
        
        function viewChatHistory(candidateId, candidateName) {
            // 跳转到聊天记录页面
            console.log(`[跳转] 查看聊天记录 - 候选人ID: ${candidateId}, 姓名: ${candidateName}`);
            window.location.href = `/user_chat.html?candidate_id=${candidateId}`;
        }
        
        async function exportResults() {
            if (!evaluationData) {
                alert('请先进行评估');
                return;
            }
            
            try {
                const response = await fetch('/api/export-evaluations', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ evaluations: evaluationData.all_evaluations || [] })
                });
                
                if (!response.ok) throw new Error('导出失败');
                
                const result = await response.json();
                alert(`成功导出 ${result.exported_count} 条结果`);
            } catch (error) {
                alert(`导出失败: ${error.message}`);
            }
        }
    </script>
</body>
</html>

